<template>
  <div class="user-assess">
    <div class="assess-header">
      <div class="header-left">
        <h3>商品评价列表</h3>
        <p>商品ID: {{ productId }}</p>
      </div>
      <el-button type="primary" @click="handleAddReview">发表评价</el-button>
    </div>
    
    <div v-if="loading" class="loading">
      <el-loading :loading="true" text="加载中..."></el-loading>
    </div>
    
    <div v-else-if="fullAssessList.length === 0" class="empty">
      <el-empty description="暂无评价数据"></el-empty>
    </div>
    
    <div v-else class="assess-list">
      <el-card v-for="(item, index) in displayedAssessList" :key="index" class="assess-item">
        <div class="assess-header">
          <div class="user-info">
            <el-avatar v-if="item.isAnonymous" :size="40" style="background-color: #ccc;">
              <el-icon><QuestionFilled /></el-icon>
            </el-avatar>
            <el-avatar v-else :size="40" icon="UserFilled" />
            <div class="user-details">
              <div class="username">
                {{
                  item.isAnonymous
                    ? '匿名用户'
                    : item.userId === userStore.userInfo?.id
                    ? '我'
                    : `用户 ${item.userId}`
                }}
              </div>
              <div class="rating">
                <el-rate v-model="item.rating" disabled show-score />
              </div>
            </div>
          </div>
        </div>
        
        <div class="assess-content">
          <p>{{ item.content }}</p>
          <div class="media-container" v-if="(item.images && item.images.length > 0) || (item.videos && item.videos.length > 0)">
            <el-image
              v-for="(img, idx) in item.images"
              :key="'img-' + idx"
              :src="img"
              style="width:100px; height:100px; margin-right: 10px;"
              :preview-src-list="item.images"
              fit="cover"
            />
            <video
              v-for="(vid, idx) in item.videos"
              :key="'vid-' + idx"
              :src="vid"
              style="width:160px; height:100px; margin-right: 10px;"
              controls
            />
          </div>
        </div>
        
        <div class="assess-actions">
          <el-button type="primary" plain size="small" @click="handleAdditionalReview(item)">
            追评
          </el-button>
          <el-button type="success" plain size="small" @click="handleViewAdditionalReviews(item)">
            查看追评
          </el-button>
          <el-button
            v-if="item.userId === userStore.userInfo?.id"
            type="danger"
            plain
            size="small"
            @click="handleDelete(item)"
          >
            删除
          </el-button>
        </div>
      </el-card>
      <div v-if="fullAssessList.length > 3 && !showAll" class="view-more-container">
        <el-button type="primary" plain @click="handleViewMore">查看更多评价</el-button>
      </div>
    </div>

    <!-- 追评弹窗 -->
    <el-dialog v-model="dialogVisible" title="发表追评" width="500px">
      <el-form :model="additionalForm">
        <el-form-item label="追评内容">
          <el-input
            v-model="additionalForm.content"
            type="textarea"
            :rows="4"
            placeholder="请输入追评内容"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitAdditionalReview">提交</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 查看追评弹窗 -->
    <el-dialog v-model="additionalDialogVisible" title="查看追评" width="600px">
      <div v-if="additionalList.length === 0" class="empty">
        <el-empty description="暂无追评"></el-empty>
      </div>
      <div v-else>
        <el-card v-for="add in additionalList" :key="add.additionalId" style="margin-bottom: 10px;">
          <div class="user-info">
            <el-avatar :size="30" icon="UserFilled" />
            <div class="username" style="margin-left: 10px;">
              {{ currentAssessItem.userId === userStore.userInfo?.id ? '我' : `用户 ${currentAssessItem.userId}` }}
            </div>
          </div>
          <p style="margin-top: 10px;">{{ add.content }}</p>
        </el-card>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="additionalDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 发表评价弹窗 -->
    <el-dialog v-model="addReviewDialogVisible" title="发表评价" width="500px">
      <el-form :model="newReviewForm" label-position="top">
        <el-form-item label="评分">
          <el-rate v-model="newReviewForm.rating" show-score />
        </el-form-item>
        <el-form-item label="评价内容">
          <el-input
            v-model="newReviewForm.content"
            type="textarea"
            :rows="4"
            placeholder="请输入评价内容"
          />
        </el-form-item>
        <el-form-item label="匿名评价">
          <el-switch v-model="newReviewForm.isAnonymous" />
        </el-form-item>
        <el-form-item label="上传图片/视频">
          <file-upload v-model="uploadedFiles" @update:uploading="handleUploading" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addReviewDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitNewReview" :disabled="isUploading">提交</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, watch, reactive, computed } from 'vue'
import {
  getAssessListByProductId,
  addAdditionalAssess,
  getAdditionalsByEvaluationId,
  deleteUserAssess,
  addUserAssess,
  getAssessDetail
} from '@/api/assess'
import { ElMessage, ElMessageBox } from 'element-plus'
import { UserFilled, QuestionFilled } from '@element-plus/icons-vue'
import { useUserStore } from '@/stores/user'
import FileUpload from '@/components/common/FileUpload.vue'

const userStore = useUserStore()

const props = defineProps({
  productId: {
    type: [String, Number],
    required: true
  }
})

// 响应式数据
const fullAssessList = ref([])
const showAll = ref(false)

const displayedAssessList = computed(() => {
  if (showAll.value || fullAssessList.value.length <= 3) {
    return fullAssessList.value
  }
  return fullAssessList.value.slice(0, 3)
})

const loading = ref(false)
const dialogVisible = ref(false)
const additionalDialogVisible = ref(false)
const additionalList = ref([])
const currentAssessItem = ref(null)
const addReviewDialogVisible = ref(false)

// 追评表单
const additionalForm = reactive({
  content: ''
})

const newReviewForm = reactive({
  rating: 0,
  content: '',
  isAnonymous: false,
})

const uploadedFiles = ref([]) // 存储已上传文件的URL和类型
const isUploading = ref(false) // 是否有文件正在上传

// 获取评价列表（分页）
const toRawFullAssessList = () => fullAssessList.value.map(a => a.evaluationId)

const getAssessList = async (isLoadMore = false) => {
  if (!props.productId) return
  loading.value = true
  try {
    if (!isLoadMore) {
      // 首次加载，只请求前三条
      const response = await getAssessListByProductId(props.productId, 1, 3)
      if (response.code === 200) {
        const assessments = response.data || []
        for (const assess of assessments) {
          const detailRes = await getAssessDetail(assess.evaluationId)
          if (detailRes.code === 200 && detailRes.data) {
            assess.images = detailRes.data.filter(m => m.mediaType === 1).map(m => m.mediaUrl)
            assess.videos = detailRes.data.filter(m => m.mediaType !== 1).map(m => m.mediaUrl)
          } else {
            assess.images = []
            assess.videos = []
          }
        }
        fullAssessList.value = assessments
        showAll.value = false
      } else {
        ElMessage.error(response.msg || '获取评价列表失败')
      }
    } else {
      // 加载更多，获取全部，再去掉已加载的前三条
      const response = await getAssessListByProductId(props.productId, 1, 100)
      if (response.code === 200) {
        let assessments = response.data || []
        assessments = assessments.slice(3) // 去掉前3条
        // 去重：只保留未加载过的
        const loadedIds = toRawFullAssessList()
        const newAssessments = assessments.filter(a => !loadedIds.includes(a.evaluationId))
        for (const assess of newAssessments) {
          const detailRes = await getAssessDetail(assess.evaluationId)
          if (detailRes.code === 200 && detailRes.data) {
            assess.images = detailRes.data.filter(m => m.mediaType === 1).map(m => m.mediaUrl)
            assess.videos = detailRes.data.filter(m => m.mediaType !== 1).map(m => m.mediaUrl)
          } else {
            assess.images = []
            assess.videos = []
          }
        }
        fullAssessList.value = fullAssessList.value.concat(newAssessments)
        showAll.value = true
      } else {
        ElMessage.error(response.msg || '获取评价列表失败')
      }
    }
  } catch (error) {
    console.error('获取评价列表失败:', error)
    ElMessage.error('获取评价列表失败')
  } finally {
    loading.value = false
  }
}

// "查看更多评价"按钮点击事件
const handleViewMore = () => {
  getAssessList(true)
}

// 打开追评弹窗
const handleAdditionalReview = (item) => {
  currentAssessItem.value = item
  additionalForm.content = ''
  dialogVisible.value = true
}

// 提交追评
const submitAdditionalReview = async () => {
  if (!additionalForm.content) {
    ElMessage.warning('请输入追评内容')
    return
  }
  
  const params = {
    evaluationId: currentAssessItem.value.evaluationId,
    content: additionalForm.content,
    userId: userStore.userInfo?.id
  }
  
  try {
    const response = await addAdditionalAssess(params)
    if (response.code === 200) {
      ElMessage.success('追评成功')
      dialogVisible.value = false
      // 可以在这里刷新追评列表或更新UI
    } else {
      ElMessage.error(response.msg || '追评失败')
    }
  } catch (error) {
    console.error('追评失败:', error)
    ElMessage.error('追评失败')
  }
}

// 查看追评
const handleViewAdditionalReviews = async (item) => {
  currentAssessItem.value = item
  try {
    const response = await getAdditionalsByEvaluationId(item.evaluationId)
    if (response.code === 200) {
      additionalList.value = response.data || []
      additionalDialogVisible.value = true
    } else {
      ElMessage.error(response.msg || '获取追评列表失败')
    }
  } catch (error) {
    console.error('获取追评列表失败:', error)
    ElMessage.error('获取追评列表失败')
  }
}

// 打开新增评价弹窗
const handleAddReview = () => {
  newReviewForm.rating = 0
  newReviewForm.content = ''
  newReviewForm.isAnonymous = false
  uploadedFiles.value = []
  isUploading.value = false
  addReviewDialogVisible.value = true
}

// 提交新评价
const submitNewReview = async () => {
  if (!newReviewForm.content || newReviewForm.rating === 0) {
    ElMessage.warning('请填写评分和评价内容')
    return
  }

  const params = {
    productId: props.productId,
    userId: userStore.userInfo?.id,
    content: newReviewForm.content,
    rating: newReviewForm.rating,
    isAnonymous: newReviewForm.isAnonymous ? 1 : 0,
    urls: uploadedFiles.value.map(f => f.url),
    types: uploadedFiles.value.map(f => f.type)
  }

  try {
    const response = await addUserAssess(params)
    if (response.code === 200) {
      ElMessage.success('评价成功')
      addReviewDialogVisible.value = false
      
      // 检查返回结果是否包含回复内容
      if (response.data && typeof response.data === 'string' && response.data.trim() !== '') {
        // 显示回复内容弹窗
        showReplyDialog(response.data)
      }
      
      getAssessList() // 刷新列表
    } else {
      ElMessage.error(response.msg || '评价失败')
    }
  } catch (error) {
    console.error('评价失败:', error)
    ElMessage.error('评价失败')
  }
}

// 显示回复内容弹窗
const showReplyDialog = (replyContent) => {
  ElMessageBox.alert(
    `<div style="text-align: left;">
      <h4 style="margin-bottom: 10px; color: #409EFF;">商家回复</h4>
      <p style="line-height: 1.6; color: #333;">${replyContent}</p>
    </div>`,
    '收到商家回复',
    {
      confirmButtonText: '知道了',
      dangerouslyUseHTMLString: true,
      customClass: 'reply-dialog'
    }
  )
}

const handleUploading = (status) => {
  isUploading.value = status
}

// 删除评价
const handleDelete = async (item) => {
  try {
    await ElMessageBox.confirm(
      '您确定要删除这条评价吗？此操作不可撤销。',
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    
    const params = {
      userId: item.userId,
      evaluationId: item.evaluationId,
    }
    const response = await deleteUserAssess(params)
    if (response.code === 200) {
      ElMessage.success('评价删除成功')
      fullAssessList.value = fullAssessList.value.filter(
        (assess) => assess.evaluationId !== item.evaluationId
      )
    } else {
      ElMessage.error(response.msg || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除评价失败:', error)
      ElMessage.error('删除操作失败')
    }
  }
}

// 监听productId变化
watch(() => props.productId, (newVal) => {
  if (newVal) {
    getAssessList()
  }
}, { immediate: true })
</script>

<style scoped>
.user-assess {
  padding: 20px;
}

.assess-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #eee;
}

.header-left h3 {
  margin: 0 0 5px 0;
  color: #333;
  font-size: 18px;
}

.header-left p {
  margin: 0;
  color: #666;
  font-size: 14px;
}

.loading, .empty {
  text-align: center;
  padding: 40px 0;
}

.assess-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.assess-item {
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.assess-item .assess-header {
  border-bottom: none;
  margin-bottom: 15px;
  padding-bottom: 0;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.user-details {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.username {
  font-weight: 500;
  color: #333;
  font-size: 14px;
}

.rating {
  display: flex;
  align-items: center;
}

.assess-content {
  margin-bottom: 15px;
}

.assess-content p {
  margin: 0 0 10px 0;
  line-height: 1.6;
  color: #333;
}

.media-container {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin-top: 10px;
}

.assess-actions {
  display: flex;
  gap: 10px;
  justify-content: flex-end;
  padding-top: 10px;
  border-top: 1px solid #f0f0f0;
}

.view-more-container {
  text-align: center;
  margin-top: 20px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

/* 回复弹窗样式 */
:deep(.reply-dialog) {
  border-radius: 8px;
}

:deep(.reply-dialog .el-message-box__header) {
  background: linear-gradient(135deg, #409EFF 0%, #67C23A 100%);
  color: white;
  border-radius: 8px 8px 0 0;
}

:deep(.reply-dialog .el-message-box__title) {
  color: white;
  font-weight: 600;
}

:deep(.reply-dialog .el-message-box__content) {
  padding: 20px;
  background: #f8f9fa;
}

:deep(.reply-dialog .el-message-box__message) {
  background: white;
  padding: 15px;
  border-radius: 6px;
  border-left: 4px solid #409EFF;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

:deep(.reply-dialog .el-button--primary) {
  background: #409EFF;
  border-color: #409EFF;
  border-radius: 6px;
  padding: 8px 20px;
}

:deep(.reply-dialog .el-button--primary:hover) {
  background: #66b1ff;
  border-color: #66b1ff;
}
</style>
